import { useEffect, useState } from 'react'
import Taro, { FC, useReady, useRouter, useShareAppMessage } from '@tarojs/taro'
import { catchError, filter, mergeMap, switchMap, tap } from 'rxjs/operators'
import { combineLatest, EMPTY, firstValueFrom, Subject, Subscription } from 'rxjs'
import { AtModal, AtToast } from 'taro-ui'
import { View, Text, Image, Button } from '@tarojs/components'

import Login from '@/components/loginPopup/index'
import { useAuthFacade } from '@/hooks/useAuthFacade'
import { ROOMSTATS_TYPE, ROOM_ROLE, ROOM_STATUS } from '@/constants/room'
import { useMsgFacade } from '@/hooks/useMsgFacade'
import { getLogger } from '@/utils/log'
import { CMD } from '@/constants/message'
import { Anchor, Assistant } from '@/models/LiveRoom'

import "taro-ui/dist/style/components/button.scss" // 按需引入 
import "taro-ui/dist/style/components/modal.scss";
import "taro-ui/dist/style/components/toast.scss";

import { useRoomFacade } from './useRoomFacade'
import './index.scss'

//团队管理
export const TeamManagement: FC = () => {
  const logger = getLogger("/pages/liveRoom/TeamManagement");

  const [
    roomFacade,
    roomRole,
    anchorId,
    anchorName,
    assistants,
    picUrl,
    roomStatus,
  ] = useRoomFacade();

  const [msgFacade] = useMsgFacade();

  const router = useRouter();
  // console.log(router, '路由对象')
  let action = router.params.action || "";
  const roomId = router.params.roomId || "";

  const [authFacade, loginStatus, userId, realName, orgs, userInfo, userApproveStatus, orgApproveStatus, idCardNo] = useAuthFacade();

  //登录弹窗组件相关状态
  const [clicked, setClicked] = useState(false);

  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  //存储电话号码
  const [anchorPhone, setAnchorPhone] = useState("");
  const [assistantPhone, setAssistantPhone] = useState("");

  // //弹窗相关
  const [showModel, setShowModel] = useState(true)
  const [showToast, setShowToast] = useState(false)
  const [showBtn, setShowBtn] = useState(Number)

  //主播头像
  // const [anchorAvatar, setAnchorAvatar] = useState("https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/tx.png")
  const [anchorAvatar, setAnchorAvatar] = useState(ASSETS_PATH + '/default_avator.png')
  //助理头像
  // const [assistantAvatar, setAssistantAvatar] = useState("https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/tx.png")
  const [assistantAvatar, setAssistantAvatar] = useState(ASSETS_PATH + '/default_avator.png')
  //处理弹窗
  const setShow = () => {
    setShowModel(!showModel)
    Taro.redirectTo({
      url: '/pages/index/index'
    })

  }
  const goEmpower = () => {
    setShowModel(!showModel)
    submit()
  }

  // 移除主播
  const delInviteAnchor = () => {
    if (roomStatus === ROOM_STATUS.STARTED) {
      return Taro.showToast({
        title: '直播已开始，不能移除主播了喔~',
        icon: 'none',
        duration: 1000
      })
    }
    // console.log('删除主播');
    firstValueFrom(roomFacade.delInviteAnchor(roomId));

    Taro.showToast({
      title: '删除成功',
      icon: 'none',
      duration: 1000
    })
  }

  //移除助理
  const delAssistant = () => {
    // console.log('删除主播');
    firstValueFrom(roomFacade.delAssistant(roomId, assistants[0].userId))
    Taro.showToast({
      title: '删除成功',
      icon: 'none',
      duration: 1000
    })
  }

  //更新action值后更新值
  const submit = () => {
    emitter.next(action);
  }


  //前往直播间
  const jumpRoom = () => {
    Taro.redirectTo({
      url: `/pages/liveRoom/LiveDetails/index?roomId=${roomId}`
    })
  }
  // 分享卡片的背景
  const bckImg = picUrl + '?imageMogr2/thumbnail/660x540/pad/1/color/#112233'
  // console.log('图片', picUrl);

  //邀请主播或助理 按钮
  useShareAppMessage(res => {

    if (res.from === 'button') {
      // 获取按钮传值
      const btnObj: any = res.target
      action = btnObj.dataset.name
      // action = res.target?.dataset.name
      setShowToast(true)
    }


    return {
      // title: action === 'anchor' ? '主播邀请' : '助理邀请',
      title: '诚邀您加入直播间',
      imageUrl: bckImg,
      // path: `pages/liveRoom/TeamManagement/index?roomId=${roomId}&action=${action}`,
      path: `subPages/liveRoom/TeamManagement/index?roomId=${roomId}&action=${action}`,
    }
  })
  // 受邀成为主播或助理
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      emitter.asObservable()
        .pipe(
          mergeMap(thisAction => {
            if (thisAction === 'anchor') {
              console.log('受邀成为主播')
              return roomFacade.updateInviteAnchor(roomId)
                .pipe(
                  tap(res => {
                    if (res.anchor.avatar) {
                      setAnchorAvatar(res.anchor.avatar)

                    }
                    setAnchorPhone(res.anchor.phone);
                    firstValueFrom(roomFacade.saveRoomStat(roomId, ROOMSTATS_TYPE.VISITED));
                    console.log('成功，邀请主播接口返回值', res)
                  })
                )
            } else if (thisAction === 'assistant') {
              console.log('受邀成为助理')
              return roomFacade.updateInviteAsistant(roomId)
                .pipe(
                  tap(res => {
                    if (res.assistants && res.assistants.length > 0) {
                      setAssistantAvatar(res.assistants[0].avatar)
                      setAssistantPhone(res.assistants[0].phone)
                      firstValueFrom(roomFacade.saveRoomStat(roomId, ROOMSTATS_TYPE.VISITED));
                      console.log('成功，邀请助理接口返回值', res)
                    }
                  })
                );
            } else {
              return EMPTY
            }
          }),
          catchError(err => {
            setEmitter(initSubject)
            return EMPTY
          })
        )
        .subscribe(
        )
    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])

  //监听系统通知
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      //处理系统群发通知
      roomFacade.handleGroupSystemNotify$
        .pipe(
          tap(msg => {
            //不在上一个tap内运行是考虑store更新的异步延迟问题，在本周期内才能获取最新数据
            switch (msg.cmd) {
              case CMD.ADD_INVITE_ANCHOR:
                {
                  const anchor = msg.data as Anchor;
                  setAnchorAvatar(anchor.avatar)
                  setAnchorPhone(anchor.phone)
                  console.log('msg.data返回来的头像数据', msg)
                  break;
                }
              case CMD.ADD_ASSISTANT:
                {
                  const assistant = msg.data as Assistant;
                  setAssistantAvatar(assistant.avatar)
                  setAssistantPhone(assistant.phone)
                  console.log('msg.data返回来的头像数据', msg)
                  break;
                }
              default:
                break;
            }
          })
        )
        .subscribe(),
    ]

    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  //登录im或者获取房间信息
  useEffect(() => {
    console.log("当前房间Id: ", roomId)
    //重置房间state数据
    roomFacade.resetRoomStore(roomId);
    //重置房间聊天数据
    msgFacade.resetMsgStore(roomId);

    const subscriptions: Subscription[] = [
      authFacade.loginStatus$
        .pipe(
          tap(isLogin => !isLogin && setClicked(true)),
          filter(isLogin => isLogin === true),
          switchMap(() => roomFacade.enterRoom(roomId)),
          //查询邀请状态
          switchMap(() => roomFacade.getInvites(roomId)),
        )
        .subscribe(
          res => {
            console.log('登录之后打印', res)
            if (res.anchor && res.anchor.userId) {
              setAnchorPhone(res.anchor.phone);
            }
            if (res.assistants && res.assistants.length > 0) {
              setAssistantPhone(res.assistants[0].phone)
            }
            // console.log(action, '当前身份')
          },
          console.error
        ),

      //异步加群
      combineLatest([authFacade.loginStatus$, msgFacade.isSDKReady$])
        .pipe(
          //auth store刷新后才需要重新登录IM
          filter(([isLogin, isSDKReady]) => isLogin && isSDKReady),
          tap(() => msgFacade.applyJoinBigGroup(roomId)),
        )
        .subscribe(),
    ]

    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  useReady(() => {
    // 判断上级路径是否为首页, 若长度为1，说明是点击卡片进来的
    const index = Taro.getCurrentPages()
    console.log('getCurrentPages的值', index)
    setShowBtn(index.length)
  })

  return (
    <View className='index'>
      <View className='main'>
        {/* 邀请主播 */}
        <View className='item'>
          {/* 没有主播时显示 */}
          {!anchorId && (
            <View className='item-title'>
              <Text className='text'>{(roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.OWNER_ASSISTANT) ? '目前由您直播。' : '暂无主播。'}</Text>
              {roomRole === ROOM_ROLE.OWNER_ANCHOR && <Button openType='share' data-name='anchor' className='text2'>邀请主播</Button>}
            </View>
          )}
          {/* 有主播时显示 */}
          {!!anchorId && (
            <View className='anchorMsg'>
              <View className='portrait'><Image src={anchorAvatar} className='tx-img'></Image></View>
              <View className='right'>
                <View className='right-l'>
                  <View className='left-top'>
                    <Text className='nickName'>{anchorName}</Text>
                    <View className='role'>主播</View>
                  </View>
                  <View className='left-bottom'><Text className='phone'>手机号: {anchorPhone}</Text></View>
                </View>
                {(roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.OWNER_ASSISTANT) && roomStatus === ROOM_STATUS.NOT_STARTED && (<View className='delete' onClick={delInviteAnchor}>移除主播</View>)}
              </View>
            </View>)}
          {/* 下标部分 */}
          <View className='line'></View>
          <View className='explain'>
            <View className='icon'><Image src={ASSETS_PATH + '/question.png'} className='icon-img'></Image></View>
            <View className='power'>主播权限：除团队管理外的所有直播管理功能且仅由主播进行直播</View>
          </View>
        </View>


        {/* 邀请助理 */}
        <View className='item'>
          {/* 无助理时样式 */}
          {assistants && assistants.length === 0 && (<View className='item-title'>
            <Text className='text'>暂无助理。</Text>
            {(roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.OWNER_ASSISTANT) && (<Button openType='share' data-name='assistant' className='text2'>邀请助理</Button>)}
          </View>)}

          {/* 有助理时样式 */}
          {assistants && assistants.length > 0 && (
            <View className='anchorMsg'>
              <View className='portrait'><Image src={assistantAvatar} className='tx-img'></Image></View>
              <View className='right'>
                <View className='right-l'>
                  <View className='left-top'>
                    <Text className='nickName'>{assistants[0].nickname}</Text>
                    <View className='role'>助理</View>
                  </View>
                  <View className='left-bottom'><Text className='phone'>手机号: {assistants[0].phone}</Text></View>
                </View>
                {(roomRole === ROOM_ROLE.OWNER_ANCHOR || roomRole === ROOM_ROLE.OWNER_ASSISTANT) && (<View className='delete' onClick={delAssistant}>移除助理</View>)}
              </View>
            </View>
          )}

          {/* 下标部分 */}
          <View className='line'></View>
          <View className='explain'>
            <View className='icon'><Image src={ASSETS_PATH + '/question.png'} className='icon-img'></Image></View>
            <View className='power'>助理权限：除团队管理外的所有直播管理功能</View>
          </View>
        </View>

        {/* 添加按钮返回直播间 */}
        {!!showBtn && showBtn <= 1 && (
          <View className='jump'>
            <Button onClick={jumpRoom} className='jump-room'>前往直播间</Button>
          </View>
        )}
      </View>

      {/* 授权成功提示框 */}
      <AtToast isOpened={showToast} text='操作成功'></AtToast>

      <Login clicked={clicked} setClicked={setClicked} />

      {/* 授权提示框 ，当受邀者为游客才弹出*/}
      <AtModal
        isOpened={showModel && !!action && !!loginStatus && roomRole === ROOM_ROLE.AUDIENCE}
        cancelText='取消'
        confirmText='确认'
        onCancel={setShow}
        onConfirm={goEmpower}
        content={`是否接受邀请，成为${action === 'anchor' ? '主播' : '助理'}`}
      />
    </View >
  )
}
export default TeamManagement